package s8_Hash算法;

/**
 * @author wisdomelon
 * @date 2020/7/30 0030
 * @project data_study
 * @jdk 1.8
 */
public class HashtabDemo {

    public static void main(String[] args) {

        HashTab hashTab = new HashTab(10);
        hashTab.add(new Emp(1, "admin"));
        hashTab.add(new Emp(2, "scott"));
        hashTab.list();

        System.out.println(hashTab.get(1));

    }

}

class HashTab {

    EmpLinkedList[] empLinkedLists;

    int size;

    public HashTab(int size) {
        this.empLinkedLists = new EmpLinkedList[size];
        this.size = size;
    }

    public void add(Emp emp) {
        int position = hash(emp.id);
        EmpLinkedList empLinkedList = this.empLinkedLists[position];
        if(empLinkedList == null) {
            empLinkedList = new EmpLinkedList();
        }
        empLinkedList.add(emp);
        this.empLinkedLists[position] = empLinkedList;
    }

    public void list() {
        for(EmpLinkedList empLinkedList: empLinkedLists) {
            if(empLinkedList != null) {
                empLinkedList.list();
            }
        }
    }

    public int hash(int id) {
        return id % size;
    }

    public Emp get(int id) {
        int position = hash(id);
        EmpLinkedList empLinkedList = this.empLinkedLists[position];
        if(empLinkedList == null) {
            return null;
        }
        return empLinkedList.get(id);
    }

}


class Emp{
    public int id;

    public String name;

    public Emp next;

    public Emp(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

class EmpLinkedList {

    /** 头指针 */
    private Emp head;

    /**
     * 添加
     * */
    public void add(Emp emp){
        if(head == null) {
            head = emp;
            return;
        }

        Emp cur = head;
        while(true) {
            if(cur.next == null) {
                break;
            }
            cur = cur.next;
        }
        cur.next = emp;
    }


    public void list() {
        if(head == null) {
            throw new NullPointerException();
        }

        Emp cur = head;
        do{
            System.out.println(cur);
            cur = cur.next;
        } while(cur != null);

    }

    public Emp get(int id) {
        if(head == null) {
            throw new NullPointerException();
        }

        Emp cur = head;

        do{
            if(cur.id == id) {
                return cur;
            }
            cur = cur.next;
        } while(cur != null);

        return null;

    }

}
